import React, { useState, useEffect } from 'react';
import { BookmarkNode } from '../types/bookmark';

const Navigation: React.FC = () => {
  const [bookmarks, setBookmarks] = useState<BookmarkNode[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [activeFolder, setActiveFolder] = useState<string | null>(null);
  const [menuOpen, setMenuOpen] = useState<string | null>(null);
  const [isSidebarOpen, setIsSidebarOpen] = useState(true);

  useEffect(() => {
    chrome.bookmarks.getTree((result) => {
      // 获取书签栏（通常是第一个子节点）
      const bookmarkBar = result[0].children?.[0];
      if (bookmarkBar) {
        setBookmarks([bookmarkBar]);
        setActiveFolder(bookmarkBar.id);
      }
      setLoading(false);
    });
  }, []);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuOpen && !(event.target as Element).closest('.bookmark-menu')) {
        setMenuOpen(null);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [menuOpen]);

  const handleBookmarkAction = async (action: string, bookmark: BookmarkNode) => {
    switch (action) {
      case 'copy':
        await navigator.clipboard.writeText(bookmark.url || '');
        break;
      case 'edit':
        chrome.tabs.create({ url: `chrome://bookmarks/?id=${bookmark.id}` });
        break;
      case 'delete':
        if (window.confirm('确定要删除这个书签吗？')) {
          chrome.bookmarks.remove(bookmark.id, () => {
            chrome.bookmarks.getTree((result) => {
              const bookmarkBar = result[0].children?.[0];
              if (bookmarkBar) {
                setBookmarks([bookmarkBar]);
              }
            });
          });
        }
        break;
    }
    setMenuOpen(null);
  };

  const renderFolder = (folder: BookmarkNode) => {
    if (!folder.children) return null;
    return (
      <div key={folder.id}>
        {folder.title && (
          <button
            onClick={() => setActiveFolder(folder.id)}
            className={`nav-item ${activeFolder === folder.id ? 'active' : ''}`}
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
            </svg>
            <span className="truncate">{folder.title}</span>
          </button>
        )}
        {folder.children.filter(child => child.children).map(renderFolder)}
      </div>
    );
  };

  const renderSidebar = () => (
    <div className={`sidebar ${isSidebarOpen ? 'open' : ''}`}>
      <div className="p-4">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-xl font-bold text-gray-800">书签导航</h1>
          <button 
            className="md:hidden"
            onClick={() => setIsSidebarOpen(false)}
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="space-y-1">
          {bookmarks.map(renderFolder)}
        </div>
      </div>
    </div>
  );

  const getFaviconUrl = (url: string) => {
    try {
      const urlObj = new URL(url);
      return `https://t3.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${encodeURIComponent(urlObj.origin)}&size=32`;
    } catch {
      return 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23CBD5E0" width="24" height="24"%3E%3Cpath d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/%3E%3C/svg%3E';
    }
  };

  const renderBookmarkCard = (bookmark: BookmarkNode) => {
    if (!bookmark.url) return null;
    return (
      <div key={bookmark.id} className="bookmark-card group">
        <div className="flex items-center justify-between">
          <div className="flex items-center flex-1 min-w-0">
            <div className="w-8 h-8 mr-3 flex-shrink-0 rounded-lg bg-gray-100 flex items-center justify-center overflow-hidden">
              <img
                src={getFaviconUrl(bookmark.url)}
                alt=""
                className="w-5 h-5"
                onError={(e) => {
                  (e.target as HTMLImageElement).src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23CBD5E0" width="24" height="24"%3E%3Cpath d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/%3E%3C/svg%3E';
                }}
              />
            </div>
            <div className="min-w-0">
              <h3 className="font-medium text-gray-900 truncate mb-1">
                {bookmark.title || 'Untitled'}
              </h3>
              <a
                href={bookmark.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm text-gray-500 truncate block hover:text-blue-500"
              >
                {bookmark.url}
              </a>
            </div>
          </div>
          <div className="relative">
            <button 
              className="ml-2 text-gray-400 hover:text-gray-600 opacity-0 group-hover:opacity-100 transition-opacity"
              onClick={() => setMenuOpen(menuOpen === bookmark.id ? null : bookmark.id)}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
              </svg>
            </button>
            {menuOpen === bookmark.id && (
              <div className="bookmark-menu absolute right-0 mt-2 w-48 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-10">
                <div className="py-1">
                  <button
                    className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center"
                    onClick={() => handleBookmarkAction('copy', bookmark)}
                  >
                    <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                    </svg>
                    复制链接
                  </button>
                  <button
                    className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center"
                    onClick={() => handleBookmarkAction('edit', bookmark)}
                  >
                    <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                    编辑
                  </button>
                  <button
                    className="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100 flex items-center"
                    onClick={() => handleBookmarkAction('delete', bookmark)}
                  >
                    <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                    删除
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  const getCurrentFolderBookmarks = () => {
    if (!activeFolder) return [];
    const findFolder = (nodes: BookmarkNode[]): BookmarkNode | null => {
      for (const node of nodes) {
        if (node.id === activeFolder) return node;
        if (node.children) {
          const found = findFolder(node.children);
          if (found) return found;
        }
      }
      return null;
    };
    const currentFolder = findFolder(bookmarks);
    return currentFolder?.children || [];
  };

  const filterBookmarks = (bookmarks: BookmarkNode[]) => {
    if (!searchTerm) return bookmarks;
    return bookmarks.filter(bookmark => {
      const matchesSearch = 
        bookmark.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        bookmark.url?.toLowerCase().includes(searchTerm.toLowerCase());
      return matchesSearch;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-4 border-blue-500 border-t-transparent"></div>
      </div>
    );
  }

  const currentBookmarks = getCurrentFolderBookmarks();
  const filteredBookmarks = filterBookmarks(currentBookmarks);

  return (
    <div className="flex min-h-screen">
      {renderSidebar()}
      <div className="main-content">
        <div className="mb-6 flex items-center justify-between">
          <button
            className="md:hidden mr-4"
            onClick={() => setIsSidebarOpen(true)}
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
            </svg>
          </button>
          <div className="flex-1">
            <input
              type="text"
              placeholder="搜索书签..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-4 py-2 rounded-lg border border-gray-200 focus:outline-none focus:border-blue-500"
            />
          </div>
        </div>
        <div className="bookmark-grid">
          {filteredBookmarks.filter(bookmark => bookmark.url).map(renderBookmarkCard)}
        </div>
      </div>
    </div>
  );
};

export default Navigation;
